package com.org.web.support.interceptors;

import com.org.platform.support.conponents.Web;
import com.org.platform.support.conponents.limit.Limit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class LimitInterceptor implements HandlerInterceptor {

  @Autowired
  private Web web;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String servletPath = request.getServletPath();
    Integer limitCount = web.getLimitConfig().getLimitCount();
    Long limitTime = web.getLimitConfig().getLimitTime();
    // 这个请求,3秒内范围3次
    boolean canAccess = Limit.canAccess(servletPath, limitTime, limitCount);
    if (!canAccess) {
      response.sendRedirect(request.getContextPath() + "/error/329");
      return canAccess;
    }
    return canAccess;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

  }

}
